import {Request, Response} from "express";
import Constant from "@src/util/constant";
import path from "path";
import commonSql from '@src/sql/common';
import httpStatusCodes from "@src/declarations/major/HttpStatusCodes";
import * as fs from "fs";

const paths = {
  upload: "/upload",
  tem: "/tem/:file",
};

// 图片大小限制
const ImageSize: number = 1024 * 1024;

// 上传文件
const upload = (req: any, res: Response) => {
  let fileUrl: string;
  // 是否上传文件
  if (!req.files || Object.keys(req.files).length !== 1) {
    return res.status(httpStatusCodes.BAD_REQUEST).json({data: Constant.FILE_ERROR});
  }
  // 获取信息
  const {
    mimetype,
    md5,
    name,
    size,
  } = req.files.file as { name: string, size: number, mimetype: string, md5: string, mv: any };

  // 图片文件大小限制在2m
  if (mimetype.indexOf("image") >= 0) {
    if (Number(size) > ImageSize) {
      return res.status(httpStatusCodes.BAD_REQUEST).json({data: Constant.FILE_SIZE_ERROR});
    }
  }

  // 只支持pdf、mp3、mp3、img
  if (!(mimetype.indexOf("image") >= 0 || mimetype.indexOf("video") >= 0 || mimetype.indexOf("audio") >= 0 || mimetype.indexOf("pdf") >= 0)) {
    return res.status(httpStatusCodes.BAD_REQUEST).json({
      data: Constant.FILE_TYPE_ERROR,
    });
  }

  // 索引截取后缀
  const index: number = name.lastIndexOf(".");

  // 文件存储路径
  fileUrl = path.join(__dirname, `../../fileTem/${md5}${name.substring(index)}`);

  // 存放文件到本地目录
  req?.files?.file?.mv(fileUrl, async (err: any) => {
    if (err) {
      return res.status(httpStatusCodes.INTERNAL_SERVER_ERROR).json({
        data: Constant.FILE_API_ERROR,
      });
    }

    // 文件存储路径
    const pathUrl = `${req.protocol}://${req.get('host')}/api/common/tem/${md5}${name.substring(index)}`;

    // 数字id
    const id = await commonSql.addFile(mimetype, pathUrl, size);

    // 成功
    return res.status(httpStatusCodes.OK).json({
      data: {
        ...Constant.DEFAULT_SUCCESS,
        data: {
          id,
          size,
          mimetype,
          path: pathUrl,
        },
      },
    });
  });
};

const readFile = (req: Request, res: Response) => {
  // 请求地址获取文件地址
  const fileName = req.params.file;
  // 提取文件地址
  const name = fileName.substring(fileName.lastIndexOf('/') + 1);
  // 读取本地文件地址
  const url = path.join(`${__dirname}+../../../fileTem/${name}`);
  // 开始读取
  fs.readFile(url, (err, data) => {
    // 存在失败？
    if (err) {
      // 设置请求头（反之乱码）
      res.writeHead(404, {"Content-Type": "text/plain;charset=utf-8"});
      res.write('文件不存在');
    } else {
      // 文件发送到浏览器
      res.write(data);
    }
    // 结束响应
    res.end();
  });
};

export default {
  paths,
  upload,
  readFile,
};